//
//  PlayerManager.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/11/1.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "PlayerManager.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"

@interface PlayerManager ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *avAudioPlayer;
@property (nonatomic, copy) NSString *currentPlayingSongName;
@end

@implementation PlayerManager

#pragma mark - life cycle
+ (instancetype)defaultPlayer {
    static PlayerManager *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [PlayerManager new];
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        
    });
    return player;
}

#pragma mark ********************************** AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"audioPlayerDidFinishPlaying 播放完成");
    int index = 0;
    for (NSDictionary *item in self.songs) {
        if ([[item safeObjectForKey:@"song"] isEqualToString:self.currentPlayingSongName]) {
            return;
        }
        index++;
    }
    NSString *nextSongName = [[self.songs safeObjectAtIndex:index] safeObjectForKey:@"song"];
    [self playWithName:nextSongName];
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error {
    NSLog(@"播放发生错误%@",error);
}

#pragma mark - public
- (void)playWithName:(NSString *)songName {
    BOOL theSameSong = YES;
    if (!self.currentPlayingSongName || ![self.currentPlayingSongName isEqualToString:songName]) {
        self.currentPlayingSongName = songName;
        theSameSong = NO;
    }
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:songName ofType:@"mp3"];
    NSURL *audioUrl = [NSURL fileURLWithPath:audioPath];
    NSError *playerError;
    //点击同一首歌 不需要重新加载
    //点击了不同的歌||第一次点歌 加载播放
    if (!theSameSong || !_avAudioPlayer.isPlaying) {
        self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioUrl error:&playerError];
    }
    if (_avAudioPlayer == NULL)
    {
        NSLog(@"fail to play audio :(");
        return;
    }
    [_avAudioPlayer setNumberOfLoops:0];
    [_avAudioPlayer setVolume:.5];
    [_avAudioPlayer prepareToPlay];
    [_avAudioPlayer play];
    _avAudioPlayer.delegate = self;
}
- (void)pausedOrContinuePlay {
    if (self.isPlaying) {
        [_avAudioPlayer pause];
    }else {
        [_avAudioPlayer play];
    }
}
#pragma mark - getter
- (BOOL)isPlaying {
    return [_avAudioPlayer isPlaying];
}
- (NSString *)currentPlaySongName {
    return [self.currentPlayingSongName copy];
}
- (NSArray *)songs {
    return @[@{@"song":@"Clouds",@"singer":@"Zach Sobiech"},
                   @{@"song":@"秋姉妹のなく頃に in the autumn sky",@"singer":@"ばんばんしー"},
                   @{@"song":@"Our Own Heaven",@"singer":@"Masetti"},
                   @{@"song":@"飘向北方",@"singer":@"尤长靖/那吾克热"},
                   @{@"song":@"Loving Strangers",@"singer":@"Jocelyn Pook,Russian Red"},
                   @{@"song":@"唱首歌",@"singer":@"南征北战"},
                   @{@"song":@"Booty Music",@"singer":@"Git Fresh"},
                   @{@"song":@"单飞",@"singer":@"胡灵"},
                   @{@"song":@"Jocelin",@"singer":@"Leddra Chapman"},
                   @{@"song":@"Enemy",@"singer":@"Sara Lumholdt"},
                   @{@"song":@"Tu Corres Em Mim",@"singer":@"Diana Lucas"},
                   @{@"song":@"继续",@"singer":@"NaCho"},
                   @{@"song":@"后来remix",@"singer":@"Maxone老虎"}];
}
@end
